<template>
  <div class="min-h-screen bg-gray-50">
    <!-- 加载状态 -->
    <div v-if="loading" class="container mx-auto px-4 py-8">
      <div class="flex items-center justify-center min-h-[400px]">
        <div class="text-center">
          <div class="inline-block animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mb-4"></div>
          <p class="text-gray-600">正在加载用户数据...</p>
        </div>
      </div>
    </div>

    <!-- 错误状态 -->
    <div v-else-if="error" class="container mx-auto px-4 py-8">
      <div class="flex items-center justify-center min-h-[400px]">
        <div class="text-center">
          <div class="inline-block w-12 h-12 text-red-500 mb-4">
            <svg fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L3.732 16.5c-.77.833.192 2.5 1.732 2.5z"></path>
            </svg>
          </div>
          <p class="text-red-600 mb-4">{{ error }}</p>
          <button 
            @click="loadAllUserData"
            class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
          >
            重新加载
          </button>
        </div>
      </div>
    </div>

    <!-- 用户信息卡片 -->
    <div v-else class="container mx-auto px-4 py-8">
      <div class="max-w-4xl mx-auto">
        <!-- 用户信息卡片 -->
        <div class="bg-white rounded-lg shadow-sm p-6 mb-6">
          <div class="flex items-center space-x-8">
            <!-- 头像区域 -->
            <div class="relative cursor-pointer" @click="openAvatarModal">
              <img
                :src="getAvatarUrl(authStore.user?.id || 0, authStore.user?.avatar_url || user.avatar)"
                :alt="user.username"
                class="h-24 w-24 rounded-full object-cover border-2 border-gray-200"
              />
            </div>
            
            <div class="flex-1">
              <div class="flex items-center space-x-3 mb-2">
                <h1 class="text-2xl font-bold text-gray-900">{{ user.username }}</h1>
                <span
                  :class="[
                    'px-2 py-1 rounded text-xs font-medium',
                    user.role === 'admin' ? 'bg-red-100 text-red-800' :
                    user.role === 'teacher' ? 'bg-blue-100 text-blue-800' :
                    'bg-gray-100 text-gray-800'
                  ]"
                >
                  {{ user.role === 'admin' ? '管理员' : user.role === 'teacher' ? '教师' : '普通用户' }}
                </span>
              </div>
              <p class="text-gray-600 mb-1">{{ user.title || '算法学习者' }}</p>
              <p class="text-sm text-gray-500 mb-4">{{ user.bio || '这个人很懒，什么都没有留下...' }}</p>
              
              <div class="grid grid-cols-2 md:grid-cols-4 gap-4">
                <div class="text-center p-3 bg-gray-50 rounded-lg">
                  <div class="text-xl font-bold text-gray-900">{{ user.score }}</div>
                  <div class="text-xs text-gray-600">积分</div>
                </div>
                <div class="text-center p-3 bg-gray-50 rounded-lg">
                  <div class="text-xl font-bold text-gray-900">{{ user.solved }}</div>
                  <div class="text-xs text-gray-600">通过题目</div>
                </div>
                <div class="text-center p-3 bg-gray-50 rounded-lg">
                  <div class="text-xl font-bold text-gray-900">{{ user.rank }}</div>
                  <div class="text-xs text-gray-600">排名</div>
                </div>
                <div class="text-center p-3 bg-gray-50 rounded-lg">
                  <div class="text-xl font-bold text-gray-900">{{ (user.acceptance * 100).toFixed(2) }}%</div>
                  <div class="text-xs text-gray-600">通过率</div>
                </div>
              </div>
            </div>
            
            <div class="text-right">
              <button
                @click="openEditModal"
                class="mb-2 px-4 py-2 bg-blue-600 text-white text-sm font-medium rounded-lg hover:bg-blue-700 transition-colors"
              >
                编辑资料
              </button>
              <p class="text-xs text-gray-500">
                注册于 {{ formatDate(user.createdAt) }}
              </p>
            </div>
          </div>
        </div>

        <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
          <!-- 左侧：统计信息 -->
          <div class="lg:col-span-1 space-y-4">
            <!-- 解题统计 -->
            <div class="bg-white rounded-lg shadow-sm p-4">
              <h2 class="text-lg font-semibold text-gray-900 mb-4">解题统计</h2>
              <div class="space-y-3">
                <div class="flex items-center justify-between p-2 bg-gray-50 rounded">
                  <div class="flex items-center space-x-2">
                    <div class="w-2 h-2 bg-green-500 rounded-full"></div>
                    <span class="text-gray-700 text-sm">简单</span>
                  </div>
                  <span class="font-semibold text-gray-900">{{ user.stats.easy }}</span>
                </div>
                <div class="flex items-center justify-between p-2 bg-gray-50 rounded">
                  <div class="flex items-center space-x-2">
                    <div class="w-2 h-2 bg-yellow-500 rounded-full"></div>
                    <span class="text-gray-700 text-sm">中等</span>
                  </div>
                  <span class="font-semibold text-gray-900">{{ user.stats.medium }}</span>
                </div>
                <div class="flex items-center justify-between p-2 bg-gray-50 rounded">
                  <div class="flex items-center space-x-2">
                    <div class="w-2 h-2 bg-red-500 rounded-full"></div>
                    <span class="text-gray-700 text-sm">困难</span>
                  </div>
                  <span class="font-semibold text-gray-900">{{ user.stats.hard }}</span>
                </div>
              </div>
            </div>

            <!-- 最近活动 -->
            <div class="bg-white rounded-lg shadow-sm p-4">
              <h2 class="text-lg font-semibold text-gray-900 mb-4">最近活动</h2>
              <div class="space-y-3">
                <div
                  v-for="activity in user.recentActivities"
                  :key="activity.id"
                  class="p-3 bg-gray-50 rounded"
                >
                  <p class="text-gray-900 text-sm mb-1">{{ activity.description }}</p>
                  <p class="text-xs text-gray-500">{{ formatTime(activity.timestamp) }}</p>
                </div>
              </div>
            </div>
          </div>

          <!-- 右侧：详细内容 -->
          <div class="lg:col-span-2 space-y-4">
            <!-- 标签页导航 -->
            <div class="bg-white rounded-lg shadow-sm">
              <div class="border-b border-gray-200">
                <nav class="-mb-px flex space-x-6 px-6">
                  <button
                    v-for="tab in tabs"
                    :key="tab.id"
                    :class="[
                      'py-3 px-1 border-b-2 font-medium text-sm transition-colors',
                      activeTab === tab.id
                        ? 'border-blue-500 text-blue-600'
                        : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
                    ]"
                    @click="activeTab = tab.id"
                  >
                    {{ tab.name }}
                  </button>
                </nav>
              </div>

              <div class="p-6">
                <!-- 提交记录 -->
                <div v-if="activeTab === 'submissions'">
                  <div v-if="user.submissions && user.submissions.length > 0" class="space-y-4">
                    <div
                      v-for="submission in user.submissions"
                      :key="submission.id"
                      class="flex items-center justify-between p-4 bg-gray-50 rounded-lg"
                    >
                      <div class="flex items-center space-x-4">
                        <div
                          :class="[
                            'w-4 h-4 rounded-full flex items-center justify-center',
                            submission.status === 'accepted' ? 'bg-green-500' :
                            submission.status === 'wrong-answer' ? 'bg-red-500' :
                            submission.status === 'time-limit' ? 'bg-yellow-500' :
                            'bg-gray-500'
                          ]"
                        >
                          <svg v-if="submission.status === 'accepted'" class="w-2 h-2 text-white" fill="currentColor" viewBox="0 0 20 20">
                            <path fill-rule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clip-rule="evenodd"></path>
                          </svg>
                        </div>
                        <div>
                          <div class="font-semibold text-gray-900">{{ submission.problemTitle }}</div>
                          <div class="text-sm text-gray-500">{{ submission.language }}</div>
                        </div>
                      </div>
                      <div class="text-right">
                        <div class="text-sm text-gray-500 mb-1">{{ formatTime(submission.submittedAt) }}</div>
                        <div
                          :class="[
                            'text-sm font-semibold px-3 py-1 rounded-full',
                            submission.status === 'accepted' ? 'bg-green-100 text-green-800' :
                            submission.status === 'wrong-answer' ? 'bg-red-100 text-red-800' :
                            submission.status === 'time-limit' ? 'bg-yellow-100 text-yellow-800' :
                            'bg-gray-100 text-gray-800'
                          ]"
                        >
                          {{ submission.status === 'accepted' ? '通过' : 
                             submission.status === 'wrong-answer' ? '答案错误' :
                             submission.status === 'time-limit' ? '超时' : '其他错误' }}
                        </div>
                      </div>
                    </div>
                  </div>
                  <div v-else class="text-center py-12">
                    <div class="text-gray-400 mb-4">
                      <svg class="w-16 h-16 mx-auto" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path>
                      </svg>
                    </div>
                    <h3 class="text-lg font-medium text-gray-900 mb-2">还没有提交记录哦</h3>
                    <p class="text-gray-500">快去学习吧！</p>
                  </div>
                </div>

                <!-- 收藏题目 -->
                <div v-else-if="activeTab === 'favorites'">
                  <div v-if="user.favorites && user.favorites.length > 0" class="space-y-4">
                    <div
                      v-for="favorite in user.favorites"
                      :key="favorite.id"
                      class="flex items-center justify-between p-4 bg-gray-50 rounded-lg"
                    >
                      <div>
                        <div class="font-semibold text-gray-900 mb-1">{{ favorite.title }}</div>
                        <div class="text-sm text-gray-500">{{ favorite.description }}</div>
                      </div>
                      <div class="text-right">
                        <span
                          :class="[
                            'px-2 py-1 rounded text-xs font-medium',
                            favorite.difficulty === 'Easy' ? 'bg-green-100 text-green-800' :
                            favorite.difficulty === 'Medium' ? 'bg-yellow-100 text-yellow-800' :
                            'bg-red-100 text-red-800'
                          ]"
                        >
                          {{ favorite.difficulty === 'Easy' ? '简单' : favorite.difficulty === 'Medium' ? '中等' : '困难' }}
                        </span>
                      </div>
                    </div>
                  </div>
                  <div v-else class="text-center py-12">
                    <div class="text-gray-400 mb-4">
                      <svg class="w-16 h-16 mx-auto" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1" d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z"></path>
                      </svg>
                    </div>
                    <h3 class="text-lg font-medium text-gray-900 mb-2">还没有收藏题目哦</h3>
                    <p class="text-gray-500">快去学习吧！</p>
                  </div>
                </div>

                <!-- 竞赛记录 -->
                <div v-else-if="activeTab === 'contests'">
                  <div v-if="user.contests && user.contests.length > 0" class="space-y-4">
                    <div
                      v-for="contest in user.contests"
                      :key="contest.id"
                      class="flex items-center justify-between p-4 bg-gray-50 rounded-lg"
                    >
                      <div>
                        <div class="font-semibold text-gray-900 mb-1">{{ contest.title }}</div>
                        <div class="text-sm text-gray-500">{{ contest.description }}</div>
                      </div>
                      <div class="text-right">
                        <div class="text-lg font-bold text-blue-600 mb-1">排名: #{{ contest.rank }}</div>
                        <div class="text-sm text-gray-500">得分: {{ contest.score }}</div>
                      </div>
                    </div>
                  </div>
                  <div v-else class="text-center py-12">
                    <div class="text-gray-400 mb-4">
                      <svg class="w-16 h-16 mx-auto" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1" d="M9 12l2 2 4-4M7.835 4.697a3.42 3.42 0 001.946-.806 3.42 3.42 0 014.438 0 3.42 3.42 0 001.946.806 3.42 3.42 0 013.138 3.138 3.42 3.42 0 00.806 1.946 3.42 3.42 0 010 4.438 3.42 3.42 0 00-.806 1.946 3.42 3.42 0 01-3.138 3.138 3.42 3.42 0 00-1.946-.806 3.42 3.42 0 01-4.438 0 3.42 3.42 0 00-1.946-.806 3.42 3.42 0 01-3.138-3.138 3.42 3.42 0 00-.806-1.946 3.42 3.42 0 010-4.438 3.42 3.42 0 00.806-1.946 3.42 3.42 0 013.138-3.138z"></path>
                      </svg>
                    </div>
                    <h3 class="text-lg font-medium text-gray-900 mb-2">还没有竞赛记录哦</h3>
                    <p class="text-gray-500">快去学习吧！</p>
                  </div>
                </div>

                <!-- 我的课程 -->
                <div v-else-if="activeTab === 'courses'">
                  <div class="flex justify-between items-center mb-6">
                    <h3 class="text-lg font-semibold text-gray-900">我的课程</h3>
                    <button
                      @click="goToCourses"
                      class="px-4 py-2 bg-emerald-600 text-white text-sm font-medium rounded-lg hover:bg-emerald-700 transition-colors"
                    >
                      管理课程
                    </button>
                  </div>
                  
                  <div v-if="user.courses && user.courses.length > 0" class="space-y-4">
                    <div
                      v-for="course in user.courses"
                      :key="course.id"
                      class="p-4 bg-gray-50 rounded-lg"
                    >
                      <div class="flex items-start justify-between">
                        <div class="flex-1">
                          <div class="flex items-center space-x-3 mb-3">
                            <h4 class="text-lg font-semibold text-gray-900">{{ course.title }}</h4>
                            <span
                              :class="[
                                'px-2 py-1 text-xs font-medium rounded-full',
                                course.status === 'completed' ? 'bg-green-100 text-green-800' :
                                course.status === 'in-progress' ? 'bg-blue-100 text-blue-800' :
                                'bg-gray-100 text-gray-800'
                              ]"
                            >
                              {{ course.status === 'completed' ? '已完成' : 
                                 course.status === 'in-progress' ? '进行中' : '未开始' }}
                            </span>
                            <span class="px-2 py-1 bg-gray-100 text-gray-800 text-xs font-medium rounded">
                              {{ course.difficulty }}
                            </span>
                          </div>
                          <p class="text-gray-600 mb-3">{{ course.description }}</p>
                          <div class="flex items-center space-x-4 text-sm text-gray-500">
                            <span>讲师: {{ course.instructor }}</span>
                            <span>时长: {{ course.duration }}分钟</span>
                            <span>进度: {{ course.progress }}%</span>
                          </div>
                          <!-- 进度条 -->
                          <div class="mt-3">
                            <div class="w-full bg-gray-200 rounded-full h-2">
                              <div
                                class="bg-blue-500 h-2 rounded-full"
                                :style="{ width: `${course.progress}%` }"
                              ></div>
                            </div>
                          </div>
                        </div>
                        <div class="flex space-x-2 ml-4">
                          <button
                            @click="continueCourse(course)"
                            class="px-3 py-1.5 bg-emerald-500 text-white rounded-lg hover:bg-emerald-600 transition-colors text-sm"
                          >
                            {{ course.status === 'completed' ? '重新学习' : '继续学习' }}
                          </button>
                          <button
                            @click="viewCourse(course)"
                            class="px-3 py-1.5 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors text-sm"
                          >
                            查看详情
                          </button>
                        </div>
                      </div>
                    </div>
                  </div>

                  <div v-else class="text-center py-12">
                    <div class="text-gray-400 mb-4">
                      <svg class="w-16 h-16 mx-auto" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1" d="M12 6.253v13m0-13C10.832 5.477 9.246 5 7.5 5S4.168 5.477 3 6.253v13C4.168 18.477 5.754 18 7.5 18s3.332.477 4.5 1.253m0-13C13.168 5.477 14.754 5 16.5 5c1.746 0 3.332.477 4.5 1.253v13C19.832 18.477 18.246 18 16.5 18c-1.746 0-3.332.477-4.5 1.253"></path>
                      </svg>
                    </div>
                    <h3 class="text-lg font-medium text-gray-900 mb-2">还没有课程哦</h3>
                    <p class="text-gray-500">快去学习吧！</p>
                    <p class="text-gray-500 mb-4">开始你的学习之旅，报名感兴趣的课程</p>
                    <button
                      @click="goToCourses"
                      class="px-4 py-2 bg-gradient-to-r from-emerald-600 to-teal-600 text-white rounded-lg hover:from-emerald-700 hover:to-teal-700 transition-all duration-200"
                    >
                      浏览课程
                    </button>
                  </div>
                </div>

                <!-- 我的项目 -->
                <div v-else-if="activeTab === 'projects'">
                  <div class="flex justify-between items-center mb-6">
                    <h3 class="text-lg font-semibold text-gray-900">我的项目</h3>
                    <button
                      @click="openProjectModal"
                      class="px-4 py-2 bg-blue-600 text-white text-sm font-medium rounded-lg hover:bg-blue-700 transition-colors"
                    >
                      上传项目
                    </button>
                  </div>
                  
                  <div v-if="user.projects && user.projects.length > 0" class="space-y-4">
                    <div
                      v-for="project in user.projects"
                      :key="project.id"
                      class="p-4 bg-gray-50 rounded-lg"
                    >
                      <div class="flex items-start justify-between">
                        <div class="flex-1">
                          <div class="flex items-center space-x-3 mb-3">
                            <h4 class="text-lg font-semibold text-gray-900">{{ project.title }}</h4>
                            <span
                              :class="[
                                'px-2 py-1 text-xs font-medium rounded-full',
                                project.status === 'approved' ? 'bg-green-100 text-green-800' :
                                project.status === 'pending' ? 'bg-yellow-100 text-yellow-800' :
                                project.status === 'rejected' ? 'bg-red-100 text-red-800' :
                                'bg-gray-100 text-gray-800'
                              ]"
                            >
                              {{ project.status === 'approved' ? '已通过' : 
                                 project.status === 'pending' ? '审核中' : 
                                 project.status === 'rejected' ? '已拒绝' : '草稿' }}
                            </span>
                            <span class="px-2 py-1 bg-blue-100 text-blue-800 text-xs font-medium rounded-full">
                              {{ project.type }}
                            </span>
                          </div>
                          <p class="text-gray-600 mb-4">{{ project.description }}</p>
                          <div class="flex items-center space-x-6 text-sm text-gray-500">
                            <div class="flex items-center">
                              <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                              </svg>
                              {{ formatTime(project.created_at) }}
                            </div>
                            <div class="flex items-center">
                              <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z"></path>
                              </svg>
                              {{ project.tech_stack?.join(', ') || '未指定' }}
                            </div>
                            <div class="flex items-center">
                              <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z"></path>
                              </svg>
                              {{ project.like_count || 0 }} 点赞
                            </div>
                          </div>
                        </div>
                        <div class="flex space-x-2 ml-4">
                          <button
                            @click="editProject(project)"
                            class="px-3 py-1.5 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors text-sm"
                          >
                            编辑
                          </button>
                          <button
                            @click="deleteProject(project.id)"
                            class="px-3 py-1.5 bg-red-500 text-white rounded-lg hover:bg-red-600 transition-colors text-sm"
                          >
                            删除
                          </button>
                        </div>
                      </div>
                    </div>
                  </div>
                  <div v-else class="text-center py-12">
                    <div class="text-gray-400 mb-4">
                      <svg class="w-16 h-16 mx-auto" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1" d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10"></path>
                      </svg>
                    </div>
                    <h3 class="text-lg font-medium text-gray-900 mb-2">还没有项目哦</h3>
                    <p class="text-gray-500">快去学习吧！</p>
                  </div>
                </div>

                <!-- 我的题目 -->
                <div v-else-if="activeTab === 'questions'">
                  <div class="flex justify-between items-center mb-6">
                    <h3 class="text-lg font-semibold text-gray-900">我的题目</h3>
                    <button
                      @click="openQuestionModal"
                      class="px-4 py-2 bg-green-600 text-white text-sm font-medium rounded-lg hover:bg-green-700 transition-colors"
                    >
                      创建题目
                    </button>
                  </div>
                  
                  <div v-if="user.questions && user.questions.length > 0" class="space-y-4">
                    <div
                      v-for="question in user.questions"
                      :key="question.id"
                      class="p-4 bg-gray-50 rounded-lg"
                    >
                      <div class="flex items-start justify-between">
                        <div class="flex-1">
                          <div class="flex items-center space-x-3 mb-3">
                            <h4 class="text-lg font-semibold text-gray-900">{{ question.title }}</h4>
                            <span
                              :class="[
                                'px-2 py-1 text-xs font-medium rounded-full',
                                question.status === 'approved' ? 'bg-green-100 text-green-800' :
                                question.status === 'pending' ? 'bg-yellow-100 text-yellow-800' :
                                question.status === 'rejected' ? 'bg-red-100 text-red-800' :
                                'bg-gray-100 text-gray-800'
                              ]"
                            >
                              {{ question.status === 'approved' ? '已通过' : 
                                 question.status === 'pending' ? '审核中' : 
                                 question.status === 'rejected' ? '已拒绝' : '草稿' }}
                            </span>
                            <span
                              :class="[
                                'px-2 py-1 text-xs font-medium rounded-full',
                                question.difficulty === 'Easy' ? 'bg-green-100 text-green-800' :
                                question.difficulty === 'Medium' ? 'bg-yellow-100 text-yellow-800' :
                                'bg-red-100 text-red-800'
                              ]"
                            >
                              {{ question.difficulty === 'Easy' ? '简单' : 
                                 question.difficulty === 'Medium' ? '中等' : '困难' }}
                            </span>
                          </div>
                          <p class="text-gray-600 mb-4 line-clamp-2">{{ question.content }}</p>
                          <div class="flex items-center space-x-6 text-sm text-gray-500">
                            <div class="flex items-center">
                              <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                              </svg>
                              {{ formatTime(question.created_at) }}
                            </div>
                            <div class="flex items-center">
                              <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 7h.01M7 3h5c.512 0 1.024.195 1.414.586l7 7a2 2 0 010 2.828l-7 7a2 2 0 01-2.828 0l-7-7A1.994 1.994 0 013 12V7a4 4 0 014-4z"></path>
                              </svg>
                              {{ question.tags?.map((tag: any) => getChineseTagName(tag)).join(', ') || '无标签' }}
                            </div>
                            <div class="flex items-center">
                              <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path>
                              </svg>
                              {{ question.submission_count || 0 }} 提交
                            </div>
                          </div>
                        </div>
                        <div class="flex space-x-2 ml-4">
                          <button
                            @click="editQuestion(question)"
                            class="px-3 py-1.5 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors text-sm"
                          >
                            编辑
                          </button>
                          <button
                            @click="deleteQuestion(question.id)"
                            class="px-3 py-1.5 bg-red-500 text-white rounded-lg hover:bg-red-600 transition-colors text-sm"
                          >
                            删除
                          </button>
                        </div>
                      </div>
                    </div>
                  </div>
                  <div v-else class="text-center py-12">
                    <div class="text-gray-400 mb-4">
                      <svg class="w-16 h-16 mx-auto" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path>
                      </svg>
                    </div>
                    <h3 class="text-lg font-medium text-gray-900 mb-2">还没有题目哦</h3>
                    <p class="text-gray-500">快去学习吧！</p>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 头像上传模态框 -->
    <div v-if="isAvatarModalOpen" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 animate-fade-in">
      <div class="bg-white/95 backdrop-blur-sm rounded-2xl shadow-2xl p-8 w-full max-w-md animate-scale-in">
        <div class="flex justify-between items-center mb-6">
          <h3 class="text-2xl font-bold text-gray-900">更换头像</h3>
          <button @click="closeAvatarModal" class="text-gray-500 hover:text-gray-700 transition-colors duration-200">
            <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
            </svg>
          </button>
        </div>
        
        <!-- 预览区域 -->
        <div class="flex justify-center mb-6">
          <div class="relative">
            <img
              :src="previewUrl || getAvatarUrl(authStore.user?.id || 0, authStore.user?.avatar_url || user.avatar)"
              alt="预览头像"
              class="h-40 w-40 rounded-full object-cover border-4 border-white shadow-xl"
            />
          </div>
        </div>
        
        <!-- 文件选择 -->
        <div class="mb-6">
          <label class="block text-sm font-semibold text-gray-700 mb-3">选择图片</label>
          <div class="flex items-center justify-center w-full">
            <label class="flex flex-col w-full h-32 border-2 border-dashed border-gray-300 rounded-xl hover:bg-gray-50 cursor-pointer transition-all duration-200 hover:border-blue-400">
              <div class="flex flex-col items-center justify-center pt-7">
                <svg xmlns="http://www.w3.org/2000/svg" class="w-10 h-10 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12" />
                </svg>
                <p class="pt-2 text-sm text-gray-500 font-medium">点击上传或拖放文件</p>
                <p class="text-xs text-gray-400 mt-1">支持 JPG, PNG 格式，最大 5MB</p>
              </div>
              <input type="file" class="opacity-0" accept="image/*" @change="handleFileChange" />
            </label>
          </div>
        </div>
        
        <!-- 上传进度 -->
        <div v-if="uploadProgress > 0 && uploadProgress < 100" class="mb-6">
          <div class="w-full bg-gray-200 rounded-full h-3">
            <div 
              class="bg-gradient-to-r from-blue-500 to-blue-600 h-3 rounded-full transition-all duration-300" 
              :style="{ width: uploadProgress + '%' }"
            ></div>
          </div>
          <p class="text-sm text-gray-500 mt-2 text-center font-medium">{{ uploadProgress }}% 上传中...</p>
        </div>
        
        <!-- 错误信息 -->
        <div v-if="uploadError" class="mb-6 p-4 bg-red-50 text-red-600 rounded-xl text-sm border border-red-200">
          {{ uploadError }}
        </div>
        
        <!-- 操作按钮 -->
        <div class="flex justify-end space-x-4">
          <button 
            @click="closeAvatarModal"
            class="px-6 py-3 border border-gray-300 rounded-xl text-sm font-medium text-gray-700 hover:bg-gray-50 transition-all duration-200"
          >
            取消
          </button>
          <button 
            @click="uploadAvatar"
            :disabled="!selectedFile || uploadProgress > 0"
            class="px-6 py-3 bg-gradient-to-r from-blue-600 to-purple-600 border border-transparent rounded-xl text-sm font-medium text-white hover:from-blue-700 hover:to-purple-700 disabled:opacity-50 transition-all duration-200 hover:scale-105"
          >
            确认更换
          </button>
        </div>
      </div>
    </div>

    <!-- 用户信息编辑模态框 -->
    <div v-if="isEditModalOpen" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 animate-fade-in">
      <div class="bg-white/95 backdrop-blur-sm rounded-2xl shadow-2xl p-8 w-full max-w-2xl animate-scale-in">
        <div class="flex justify-between items-center mb-6">
          <h3 class="text-2xl font-bold text-gray-900">编辑用户信息</h3>
          <button @click="closeEditModal" class="text-gray-500 hover:text-gray-700 transition-colors duration-200">
            <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
            </svg>
          </button>
        </div>
        
        <form @submit.prevent="saveUserInfo" class="space-y-6">
          <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div>
              <label class="block text-sm font-semibold text-gray-700 mb-3">用户名</label>
              <input
                v-model="editForm.username"
                type="text"
                class="w-full px-4 py-3 bg-white/70 border border-gray-200 rounded-xl focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all duration-200"
                required
              />
            </div>
            
            <div>
              <label class="block text-sm font-semibold text-gray-700 mb-3">头衔</label>
              <input
                v-model="editForm.title"
                type="text"
                class="w-full px-4 py-3 bg-white/70 border border-gray-200 rounded-xl focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all duration-200"
                placeholder="算法学习者"
              />
            </div>
          </div>
          
          <div>
            <label class="block text-sm font-semibold text-gray-700 mb-3">个人简介</label>
            <textarea
              v-model="editForm.bio"
              rows="4"
              class="w-full px-4 py-3 bg-white/70 border border-gray-200 rounded-xl focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all duration-200"
              placeholder="这个人很懒，什么都没有留下..."
            ></textarea>
          </div>
          
          <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div>
              <label class="block text-sm font-semibold text-gray-700 mb-3">邮箱</label>
              <input
                v-model="editForm.email"
                type="email"
                class="w-full px-4 py-3 bg-white/70 border border-gray-200 rounded-xl focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all duration-200"
                required
              />
            </div>
            
            <div>
              <label class="block text-sm font-semibold text-gray-700 mb-3">手机号</label>
              <input
                v-model="editForm.phone"
                type="tel"
                class="w-full px-4 py-3 bg-white/70 border border-gray-200 rounded-xl focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all duration-200"
                placeholder="请输入手机号"
              />
            </div>
          </div>
          
          <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div>
              <label class="block text-sm font-semibold text-gray-700 mb-3">学校/公司</label>
              <input
                v-model="editForm.organization"
                type="text"
                class="w-full px-4 py-3 bg-white/70 border border-gray-200 rounded-xl focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all duration-200"
                placeholder="请输入学校或公司名称"
              />
            </div>
            
            <div>
              <label class="block text-sm font-semibold text-gray-700 mb-3">专业/职位</label>
              <input
                v-model="editForm.profession"
                type="text"
                class="w-full px-4 py-3 bg-white/70 border border-gray-200 rounded-xl focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all duration-200"
                placeholder="请输入专业或职位"
              />
            </div>
          </div>
          
          <!-- 错误信息 -->
          <div v-if="editError" class="p-4 bg-red-50 text-red-600 rounded-xl text-sm border border-red-200">
            {{ editError }}
          </div>
          
          <!-- 操作按钮 -->
          <div class="flex justify-end space-x-4 pt-4">
            <button 
              type="button"
              @click="closeEditModal"
              class="px-6 py-3 border border-gray-300 rounded-xl text-sm font-medium text-gray-700 hover:bg-gray-50 transition-all duration-200"
            >
              取消
            </button>
            <button 
              type="submit"
              :disabled="isSaving"
              class="px-6 py-3 bg-gradient-to-r from-blue-600 to-purple-600 border border-transparent rounded-xl text-sm font-medium text-white hover:from-blue-700 hover:to-purple-700 disabled:opacity-50 transition-all duration-200 hover:scale-105"
            >
              <svg v-if="isSaving" class="animate-spin -ml-1 mr-2 h-4 w-4 text-white inline" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
              </svg>
              {{ isSaving ? '保存中...' : '保存修改' }}
            </button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getAvatarUrl, getChineseTagName } from '@/utils'
import { useAuthStore } from '@/stores/auth'
import { userApi } from '@/api/user'
import { questionApi } from '@/api/question'
import { courseApi } from '@/api/course'
import { projectApi } from '@/api/project'


const route = useRoute()
const router = useRouter()
const authStore = useAuthStore()

// 头像上传相关状态
const isAvatarModalOpen = ref(false)
const selectedFile = ref<File | null>(null)
const previewUrl = ref('')
const uploadProgress = ref(0)
const uploadError = ref('')

// 用户信息编辑相关状态
const isEditModalOpen = ref(false)
const isSaving = ref(false)
const editError = ref('')
const editForm = ref({
  username: '',
  title: '',
  bio: '',
  email: '',
  phone: '',
  organization: '',
  profession: ''
})

// 响应式数据
const activeTab = ref('submissions')
const loading = ref(false)
const error = ref('')

const tabs = [
  { id: 'submissions', name: '提交记录' },
  { id: 'favorites', name: '收藏题目' },
  { id: 'contests', name: '竞赛记录' },
  { id: 'courses', name: '我的课程' },
  { id: 'projects', name: '我的项目' },
  { id: 'questions', name: '我的题目' }
]

// 用户数据 - 基于真实API
const user = ref({
  id: 0,
  username: '',
  avatar: '',
  title: '',
  bio: '',
  role: '',
  score: 0,
  solved: 0,
  rank: 0,
  acceptance: 0,
  email: '',
  phone: '',
  organization: '',
  profession: '',
  createdAt: new Date(),
  stats: {
    easy: 0,
    medium: 0,
    hard: 0
  },
  recentActivities: [] as any[],
  submissions: [] as any[],
  favorites: [] as any[],
  contests: [] as any[],
  courses: [] as any[],
  projects: [] as any[],
  questions: [] as any[]
})

// 用户信息编辑相关方法
const openEditModal = () => {
  // 初始化编辑表单数据
  editForm.value = {
    username: user.value.username,
    title: user.value.title || '',
    bio: user.value.bio || '',
    email: user.value.email || '',
    phone: user.value.phone || '',
    organization: user.value.organization || '',
    profession: user.value.profession || ''
  }
  isEditModalOpen.value = true
  editError.value = ''
}

const closeEditModal = () => {
  isEditModalOpen.value = false
  editError.value = ''
}

const saveUserInfo = async () => {
  isSaving.value = true
  editError.value = ''
  
  try {
    // 这里调用更新用户信息的API
    // const response = await userApi.updateUserInfo(editForm.value)
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 更新本地用户数据
    user.value.username = editForm.value.username
    user.value.title = editForm.value.title
    user.value.bio = editForm.value.bio
    user.value.email = editForm.value.email
    user.value.phone = editForm.value.phone
    user.value.organization = editForm.value.organization
    user.value.profession = editForm.value.profession
    
    // 更新全局用户信息
    if (authStore.user) {
      authStore.user.username = editForm.value.username
      authStore.user.email = editForm.value.email
    }
    
    console.log('用户信息更新成功:', editForm.value)
    
    // 关闭模态框
    closeEditModal()
    
    // 显示成功提示
    alert('用户信息更新成功！')
    
  } catch (error: any) {
    editError.value = error.response?.data?.message || '更新失败，请重试'
  } finally {
    isSaving.value = false
  }
}

// 头像上传相关方法
const openAvatarModal = () => {
  isAvatarModalOpen.value = true
  // 重置状态
  uploadError.value = ''
  uploadProgress.value = 0
}

const closeAvatarModal = () => {
  isAvatarModalOpen.value = false
  // 清除选择的文件和预览
  selectedFile.value = null
  previewUrl.value = ''
}

const handleFileChange = (e: Event) => {
  const input = e.target as HTMLInputElement
  if (input.files && input.files[0]) {
    const file = input.files[0]
    
    // 验证文件类型
    if (!file.type.startsWith('image/')) {
      uploadError.value = '请选择图片文件'
      input.value = '' // 重置input的value
      return
    }
    
    // 验证文件大小 (5MB)
    if (file.size > 5 * 1024 * 1024) {
      uploadError.value = '文件大小不能超过5MB'
      input.value = '' // 重置input的value
      return
    }
    
    // 清除错误信息
    uploadError.value = ''
    
    // 保存文件引用
    selectedFile.value = file
    // console.log(selectedFile.value);
    // console.log(file);
    
    // 生成预览
    const reader = new FileReader()
    reader.onload = (e) => {
      previewUrl.value = e.target?.result as string
    }
    reader.readAsDataURL(file)
  } else {
    // 如果没有选择文件，重置input的value
    input.value = ''
  }
}

const uploadAvatar = async () => {
  if (!selectedFile) return
  
  uploadProgress.value = 0
  uploadError.value = ''
  
  try {
    const formData = new FormData()
    if (!selectedFile.value) return
    formData.append('avatar', selectedFile.value)
    // console.log(formData.get('avatar'));
    
    // 调用API上传头像，使用新的接口方法
    const response = await authStore.changeAvatar(formData)
    
    if (!response?.success) {
      throw new Error(response?.message || '上传失败')
    }

    // 处理上传成功，根据新的响应结构
    if (response.data?.avatar_url) {
      // 更新本地用户数据
      user.value.avatar = response.data.avatar_url
      
      // 更新全局存储的用户信息
      if (authStore.user) {
        authStore.user.avatar_url = response.data.avatar_url
      }
      
      // 可以显示API返回的成功消息
      console.log(response.data.message)
      
      // 延迟关闭模态框
      setTimeout(closeAvatarModal, 500)
    }
  } catch (error: any) {
    // 处理上传失败
    uploadError.value = error.response?.data?.message || '上传失败，请重试'
    uploadProgress.value = 0
  }
}

// 其他方法
const formatDate = (date: Date) => {
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'long',
    day: 'numeric'
  })
}

const formatTime = (date: Date) => {
  const now = new Date()
  const diff = now.getTime() - date.getTime()
  
  if (diff < 1000 * 60) {
    return '刚刚'
  } else if (diff < 1000 * 60 * 60) {
    return `${Math.floor(diff / (1000 * 60))}分钟前`
  } else if (diff < 1000 * 60 * 60 * 24) {
    return `${Math.floor(diff / (1000 * 60 * 60))}小时前`
  } else {
    return `${Math.floor(diff / (1000 * 60 * 60 * 24))}天前`
  }
}

// 项目相关方法
const openProjectModal = () => {
  // 跳转到创建项目页面
  router.push('/projects/create')
}

const editProject = (project: any) => {
  console.log('编辑项目:', project)
  // 跳转到项目编辑页面
  // router.push(`/edit-project/${project.id}`)
}

const deleteProject = async (projectId: number) => {
  if (confirm('确定要删除这个项目吗？')) {
    try {
      // 调用删除项目API
      // await projectApi.deleteProject(projectId)
      console.log('删除项目:', projectId)
      // 从本地数据中移除
      user.value.projects = user.value.projects.filter(p => p.id !== projectId)
    } catch (error) {
      console.error('删除项目失败:', error)
      alert('删除失败，请重试')
    }
  }
}

// 题目相关方法
const openQuestionModal = () => {
  // 跳转到创建题目页面
  router.push('/questions/create')
}

const editQuestion = (question: any) => {
  console.log('编辑题目:', question)
  // 跳转到题目编辑页面
  // router.push(`/edit-question/${question.id}`)
}

const deleteQuestion = async (questionId: number) => {
  if (confirm('确定要删除这道题目吗？')) {
    try {
      // 调用删除题目API
      // await questionApi.deleteQuestion(questionId)
      console.log('删除题目:', questionId)
      // 从本地数据中移除
      user.value.questions = user.value.questions.filter(q => q.id !== questionId)
    } catch (error) {
      console.error('删除题目失败:', error)
      alert('删除失败，请重试')
    }
  }
}

// 课程相关方法
const goToCourses = () => {
  // 检查用户是否已登录
  if (!authStore.isAuthenticated) {
    console.log('用户未登录，跳转到登录页面')
    router.push('/login')
    return
  }
  
  // 使用当前登录用户的ID
  const currentUserId = authStore.user?.id || user.value.id
  
  // 跳转到课程管理页面
  router.push(`/courses/${currentUserId}`)
}

const continueCourse = (course: any) => {
  console.log('继续学习课程:', course)
  // 跳转到课程学习页面
  router.push(`/course-detail/${course.id}`)
}

const viewCourse = (course: any) => {
  console.log('查看课程详情:', course)
  // 跳转到课程详情页面
  router.push(`/course-detail/${course.id}`)
}


// 加载用户基本信息
const loadUserProfile = async () => {
  if (!authStore.isAuthenticated) return
  
  try {
    const userId = authStore.user!.id
    const response = await userApi.getUserProfile(userId)
    
    if (response.code === 200 && response.data) {
      const profileData = response.data
      user.value.id = profileData.id
      user.value.username = profileData.username
      user.value.avatar = profileData.avatar_url || '/static/avatar/default.jpg'
      user.value.email = profileData.email
      user.value.role = profileData.role
      user.value.createdAt = new Date(profileData.created_at)
      
      // 如果有扩展信息
      if (profileData.stats) {
        user.value.stats = {
          easy: profileData.stats.easy_solved,
          medium: profileData.stats.medium_solved,
          hard: profileData.stats.hard_solved
        }
      }
    }
  } catch (error) {
    console.error('加载用户信息失败:', error)
  }
}

// 加载用户统计信息
const loadUserStats = async () => {
  if (!authStore.isAuthenticated) return
  
  try {
    const response = await userApi.getCurrentUserStats()
    
    if (response.code === 200 && response.data) {
      const stats = response.data
      user.value.solved = stats.solved_count
      user.value.acceptance = stats.acceptance_rate
      user.value.stats = {
        easy: stats.difficulty_stats.easy_solved,
        medium: stats.difficulty_stats.medium_solved,
        hard: stats.difficulty_stats.hard_solved
      }
    }
  } catch (error) {
    console.error('加载用户统计失败:', error)
  }
}

// 加载用户提交记录
const loadUserSubmissions = async () => {
  if (!authStore.isAuthenticated) return
  
  try {
    const userId = authStore.user!.id
    const response = await userApi.getUserSubmissions(userId, { page: 1, page_size: 10 })
    console.log('提交记录API响应:', response)
    
    if (response.code === 200 && response.data && response.data.data) {
      user.value.submissions = response.data.data.map((submission: any) => ({
        id: submission.id,
        problemTitle: submission.question_title,
        language: submission.language,
        status: submission.status,
        submittedAt: new Date(submission.created_at)
      }))
    } else {
      console.log('提交记录数据为空或格式不正确:', response)
      user.value.submissions = []
    }
  } catch (error) {
    console.error('加载提交记录失败:', error)
    user.value.submissions = []
  }
}

// 加载用户收藏题目
const loadUserFavorites = async () => {
  if (!authStore.isAuthenticated) return
  
  try {
    const response = await questionApi.getFavoriteQuestions({ page: 1, page_size: 10 })
    console.log('收藏题目API响应:', response)
    
    if (response.code === 200 && response.data && response.data.items) {
      user.value.favorites = response.data.items.map((question: any) => ({
        id: question.id,
        title: question.title,
        description: question.content || question.description,
        difficulty: question.difficulty
      }))
    } else {
      console.log('收藏题目数据为空或格式不正确:', response)
      user.value.favorites = []
    }
  } catch (error) {
    console.error('加载收藏题目失败:', error)
    user.value.favorites = []
  }
}

// 加载用户课程数据
const loadUserCourses = async () => {
  if (!authStore.isAuthenticated) return
  
  try {
    const userId = authStore.user!.id
    const response = await courseApi.getUserCourses(userId, { page: 1, page_size: 10 })
    
    if (response && response.items) {
      user.value.courses = response.items.map((course: any) => ({
        id: course.id,
        title: course.title,
        description: course.description,
        instructor: course.instructor,
        duration: course.duration,
        difficulty: course.difficulty === 'beginner' ? '初级' : 
                   course.difficulty === 'medium' ? '中级' : '高级',
        status: course.is_completed ? 'completed' : 
                course.is_enrolled ? 'in-progress' : 'not-started',
        progress: course.progress || 0
      }))
    } else {
      user.value.courses = []
    }
  } catch (error) {
    console.error('加载用户课程失败:', error)
    user.value.courses = []
  }
}

// 加载用户项目数据
const loadUserProjects = async () => {
  if (!authStore.isAuthenticated) return
  
  try {
    const response = await projectApi.getUserProjects(authStore.user!.id, { page: 1, page_size: 10 })
    
    if (response.code === 200 && response.data && response.data.items) {
      user.value.projects = response.data.items.map((project: any) => ({
        id: project.id,
        title: project.title,
        description: project.description,
        type: project.type,
        status: project.status,
        tech_stack: project.tech_stack,
        like_count: project.like_count,
        view_count: project.view_count,
        created_at: new Date(project.created_at)
      }))
    } else {
      console.log('项目数据为空或格式不正确:', response)
      user.value.projects = []
    }
  } catch (error) {
    console.error('加载用户项目失败:', error)
    user.value.projects = []
  }
}

// 加载用户创建的题目
const loadUserQuestions = async () => {
  if (!authStore.isAuthenticated) return
  
  try {
    // 暂时使用空数组，因为questionApi中没有getUserQuestions方法
    // 可以后续添加这个API或者使用其他方法获取用户创建的题目
    user.value.questions = []
    
    // TODO: 实现获取用户创建题目的API
    // const response = await questionApi.getUserQuestions(authStore.user!.id, { page: 1, page_size: 10 })
    // if (response.code === 200 && response.data) {
    //   user.value.questions = response.data.items.map((question: any) => ({
    //     id: question.id,
    //     title: question.title,
    //     content: question.content,
    //     difficulty: question.difficulty,
    //     status: question.status,
    //     tags: question.tags,
    //     submission_count: question.submission_count,
    //     created_at: new Date(question.created_at)
    //   }))
    // }
  } catch (error) {
    console.error('加载用户题目失败:', error)
  }
}

// 加载所有用户数据
const loadAllUserData = async () => {
  if (!authStore.isAuthenticated) {
    console.log('用户未登录，无法加载数据')
    return
  }
  
  loading.value = true
  error.value = ''
  
  try {
    // 并行加载所有数据以提高性能
    await Promise.all([
      loadUserProfile(),
      loadUserStats(),
      loadUserSubmissions(),
      loadUserFavorites(),
      loadUserCourses(),
      loadUserProjects(),
      loadUserQuestions()
    ])
    
    console.log('所有用户数据加载完成')
  } catch (err) {
    console.error('加载用户数据失败:', err)
    error.value = '加载用户数据失败，请稍后重试'
  } finally {
    loading.value = false
  }
}

onMounted(async () => {
  const userId = route.params.id
  try {
    console.log('加载用户详情:', userId)
    
    // 加载所有用户数据
    await loadAllUserData()
  } catch (error) {
    console.error('加载用户详情失败:', error)
  }
})
</script>
